package com.data.controller;

import com.data.Const;
import com.data.controller.report.LogController;
import com.data.domain.report.Areainfo;
import com.data.domain.user.Userinfo;
import com.data.josonbean.auth.Auth;
import com.data.model.AuthModel;
import com.data.model.LoginModel;
import com.data.model.SystemModel;
import com.data.service.system.AreainfoService;
import com.data.service.user.AuthService;
import com.data.utill.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by silenceholic on 2017/5/4.
 */
@Controller
@RequestMapping("/auth")
public class AuthController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Resource(name = "authService")
    private AuthService authService;

    @Resource(name = "areainfoService")
    private AreainfoService areainfoService;

    /**
     *登陆跳转，同时转发
     * @param loginModel
     * @param back
     * @return
     */
    @RequestMapping(value = "/login.htm")
    public ModelAndView login(@ModelAttribute LoginModel loginModel,
                              @RequestParam(value = "back",required = false) String back){
        Map<String,Object> map = new HashMap<String, Object>();
        map = new HashMap<String, Object>();


//        map.put("app","127.0.0.1");
        map.put("back",back);
        ModelAndView mv = super.modelAndView(map);
        mv.setViewName("/auth/login");
        return mv;
    }


    /**
     *登出
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout.do")
    public ModelAndView logout(HttpServletRequest request) {
        Object sysUser = request.getSession().getAttribute(Const.SESSION_USER);
        ModelAndView mv = super.modelAndView(null);
        Short i =0;
        if (null!=sysUser && authService.updateUserState((Auth)sysUser,i)==1) {
            request.getSession().removeAttribute(Const.SESSION_USER);
            mv.setViewName("/auth/login");
        }else{
            mv.setViewName("/auth/login");
        }

        return mv;
    }

    /**
     *登陆操作
     * @param loginModel
     * @param back
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "/login.do", method = RequestMethod.POST)
    public Object doLogin(@ModelAttribute LoginModel loginModel,
                          @RequestParam(value = "back", required = false) String back,
                          HttpServletRequest request,
                          HttpSession session) {
//接受参数
//        StringBuffer buffer = new StringBuffer();
//        buffer.append(homeResource.getAuthUrl());
//        buffer.append("http://127.0.0.1");
//        buffer.append(Const.AUTH_URL_USERINFO);
//        Map<String, String> params = new HashMap<String, String>();
//        params.put("userid", loginModel.getUserid());
//        params.put("password", loginModel.getPassword());
//        params.put("FKEY", super.getFKey(loginModel.getUsername()));

        ModelAndView mv = super.modelAndView(null);

        mv.addObject("userid", loginModel.getUserid());
        mv.addObject("password", loginModel.getPassword());
        //判断用户是不是首次登陆
//        int countUser=authService.countUser();
//        if(countUser < 1 && loginModel.getUsername().equals("admin")){
//            authService.insertAdmin(loginModel.getPassword());
//        }
        try {
//            Object sysUser = authSerice.getUserByNameAndPwd(loginModel.getUsername(),loginModel.getPassword());

            Auth auth = authService.getUserByIdAndPwd(loginModel.getUserid(),loginModel.getPassword());

            if (auth!=null){
                switch (auth.getReturnCode()){
                    case 0:
                        saveSysUser(auth, request);
                        if (DateUtil.getToday().compareTo(auth.getUser().getExpiredate())<0) {
                            if (StringUtils.isNotEmpty(back)) {
//                            return "redirect:/" + request.getQueryString().substring(6);
                                return "redirect:" + back;
                            } else {
                                return "redirect:/test.htm";/*回到首页也可以用 /index.htm*/
                            }
                        }else{
                            return "redirect:/auth/changePassword.htm" ;
                        }

                    case 1:
                        mv.addObject("error", Const.ERROR_AUTH_ERROR);
                        break;
                    case 2:
                        mv.addObject("error", Const.ERROR_PSW_ERROR);
                        break;
                    case 3:
                        mv.addObject("error", Const.ERROR_LOGIN_ERROR);
                        break;
                }
            }
        } catch (Exception e) {
            mv.addObject("error", Const.ERROR_SYSTEM_ERROR);
            logger.error("System error", e);
        }
        mv.setViewName("auth/login");
        return mv;
    }


    /**
     * 返回修改密码页面
     *
     * @return
     */
    @RequestMapping(value = "/changePassword.htm", method = RequestMethod.GET)
    public Object changePassword() {
        ModelAndView mv = super.modelAndView(null);
        mv.addObject("user", super.getAuth().getUser());
        mv.setViewName("auth/password");
        return mv;
    }


    /**
     *修改密码
     * @param passwd
     * @return
     */
    @RequestMapping(value = "/changePassword.do", method = RequestMethod.POST)
    public ModelAndView doChangePassword(@RequestParam(value = "password", required = false) String passwd,
                                         HttpSession session) {

        ModelAndView mv = super.modelAndView(null);
        mv.addObject("user", super.getAuth().getUser());
        try {
            if (authService.passwd(super.getAuth(),passwd)==1) {
                mv.addObject("result", 0);
                session.removeAttribute(Const.SESSION_USER);
                mv.setViewName("auth/login");
                return mv;
            }
        } catch (Exception e) {
            mv.addObject("result", 1);
            mv.addObject("message", "修改密码失败,发生系统错误。");
            logger.error("发生系统错误", e);
        }

        mv.setViewName("auth/password");
        return mv;
    }

    /**
     * 注册用户跳转
     * @return
     */
    @RequestMapping(value = "/register.htm")
    public ModelAndView registerDispatch(){
        ModelAndView mv = super.modelAndView(null);
        if(authService.countUser()!=0){
            mv.addObject("admin",1);
        }else{
            mv.addObject("admin",0);
        }
        mv.setViewName("auth/register");
        return mv;
    }

    /**
     * 注册用户
     * @return
     */
    @RequestMapping(value = "/register.do")
    public Object register(@RequestParam(value = "userid", required = false) String userid,
                           @RequestParam(value = "username", required = false) String username,
                                 @RequestParam(value = "password", required = false) String passwd,
                                 @RequestParam(value = "role", required = false) String role){
        AuthModel authModel = new AuthModel();
        ModelAndView mv = super.modelAndView(null);
        if(authService.countUser()!=0){
            mv.addObject("admin",1);
        }else{
            mv.addObject("admin",0);
        }
        authModel.setUserid(userid);
        authModel.setUsername(username);
        authModel.setPassword(passwd);
        authModel.setRole(role);
        if (role!="0") {
            authModel.setAreacode("3310");
        }else{
            authModel.setAreacode("3300");
        }
        authModel.setUserstate("0");
        authModel.setPermission("0");
        authModel.setExpiredate(DateUtil.getTimePast(90));
//        int i =authService.insertUser(authModel);
        switch(authService.insertUser(authModel)){
            case 0:
                mv.addObject("error", Const.ERROR_ADD_FAIUL_ERROR);
                break;
            case 1:
                return "redirect:/auth/login.htm";
            case 3:
                mv.addObject("error", Const.ERROR_ADD_ERROR);
                break;
        }
        mv.setViewName("auth/register");
        return mv;
//        return "redirect:auth/login.htm";
    }

    /**
     * 增加用户
     * @param authModel
     * @return
     */
    @RequestMapping(value = "/adduser.do", method = RequestMethod.POST)
    public Object doAddUser(@ModelAttribute AuthModel authModel){
        ModelAndView mv = super.modelAndView(null);
        switch(authService.insertUser(authModel)){
            case 0:
                mv.addObject("error", Const.ERROR_ADD_FAIUL_ERROR);
                break;
            case 1:
                return "redirect:/test.htm";
            case 3:
                mv.addObject("error", Const.ERROR_ADD_ERROR);
                break;
        }
        mv.setViewName("auth/add");
        return mv;
//        return "redirect:test.htm";
    }

    /**
     * 管理用户
     * @return
     */
    @RequestMapping(value = "/manageuser.htm")
    public ModelAndView manageUser(HttpSession session){

        Map<String, Object> map = new HashMap<String, Object>();
        String areacode = ((Auth)session.getAttribute(Const.SESSION_USER)).getUser().getAreacode();
        Short role = ((Auth)session.getAttribute(Const.SESSION_USER)).getUser().getRole();
        List<Userinfo> data = authService.getAllUsers(null);
        if (role!=0) {
            data = authService.getAllUsers(areacode);
        }
        map.put("data",data);
        map.put("areainfo", areainfoService.getAreainfo(new SystemModel()));
        map.put("recordsTotal", data.size());
        map.put("recordsFiltered", data.size());
        ModelAndView mv = super.modelAndView(map);

        mv.setViewName("auth/manageuser");
        return mv;
    }

    /**
     * 修改用户跳转
     * @param id
     * @return
     */
    @RequestMapping(value = "/modifyuser.htm")
    public ModelAndView modifyUserDis(@RequestParam(value = "id", required = false) String id){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("areainfo", areainfoService.getAreainfo(new SystemModel()));
        map.put("data",authService.selectAllUsersById(id));
        ModelAndView mv = super.modelAndView(map);

        mv.setViewName("auth/modifyuser");
        return mv;
    }

    /**
     * 修改用户
     * @param authModel
     * @return
     */
    @RequestMapping(value = "/modifyuser.do", method = RequestMethod.POST)
    public String modifyAddUser(@RequestParam(value = "id", required = false) String id,
                                @ModelAttribute AuthModel authModel){
        authService.modifyUser(id , authModel);
        return "test";
    }


    /**
     * 保存用户信息进入session并持久化
     *
     * @param auth
     * @param request
     */
    private void saveSysUser(Auth auth, HttpServletRequest request) {
        try {
//            auth1.setLastlogin(new Date(System.currentTimeMillis()));
            Short i =1;
            if (authService.updateUserState(auth,i) == 1) {
                request.getSession().setAttribute(Const.SESSION_USER, auth);
            }
        } catch (Exception e) {
            logger.error("Update sysuser failed", e);
            System.out.println("Update sysuser failed");
        }
    }
}
